package route

import (
	"gitee.com/xluomo945/fm/fresponse"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func process[T any, S any](fn handler[T, S]) gin.HandlerFunc {
	creator := newCreator[T]()
	// 创建请求路由handler
	return func(ctx *gin.Context) {
		var data = creator.Create()
		if creator.isStruct {
			if err := binder(ctx, data.Ptr()); err != nil {
				fresponse.Format(ctx, nil, err)
				return
			}
		}
		resp, err := fn(ctx, data.Value())
		fresponse.Format(ctx, resp, err)
	}
}

func binder(ctx *gin.Context, dto any) error {
	_ = ctx.ShouldBindUri(dto)
	_ = ctx.ShouldBindQuery(dto)
	_ = ctx.ShouldBindJSON(dto)
	_ = ctx.ShouldBindHeader(dto)

	// 参数绑定结束统一验证
	if err := binding.Validator.ValidateStruct(dto); err != nil {
		return err
	}
	return nil
}
